/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.purchaseorder.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.dto.apply.PurchaseorderSearchDTO;
import com.fuyao.cloud.asset.entity.AssetPurchaseorder;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.asset.vo.purchaseorder.PurchaseOrderExcelVO;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.purchaseorder.service.AssetPurchaseorderService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 采购订单
 *
 * @author liyue
 * @date 2021-11-24 10:55:26
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fyassetpurchaseorder")
@Api(value = "fyassetpurchaseorder", tags = "采购订单管理")
public class AssetPurchaseorderController implements FlowableController {

	private final AssetPurchaseorderService fyAssetPurchaseorderService;

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param searchDTO 采购订单
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_view')")
	public R getFyAssetPurchaseorderPage(Page page, PurchaseorderSearchDTO searchDTO) {
		return R.ok(fyAssetPurchaseorderService.page(page, SpliceQueryWrapper.spliceSearchCondition(searchDTO),searchDTO));
	}


	/**
	 * 通过id查询采购订单
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(fyAssetPurchaseorderService.getById(id));
	}

	/**
	 * 新增采购订单
	 *
	 * @param fyAssetPurchaseorder 采购订单
	 * @return R
	 */
	@ApiOperation(value = "新增采购订单", notes = "新增采购订单")
	@SysLog("新增采购订单")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_add')")
	public R save(@RequestBody AssetPurchaseorder fyAssetPurchaseorder) {
		fyAssetPurchaseorderService.save(fyAssetPurchaseorder);
		return R.ok(fyAssetPurchaseorder);
	}

	/**
	 * 修改采购订单
	 *
	 * @param fyAssetPurchaseorder 采购订单
	 * @return R
	 */
	@ApiOperation(value = "修改采购订单", notes = "修改采购订单")
	@SysLog("修改采购订单")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_edit')")
	public R updateById(@RequestBody AssetPurchaseorder fyAssetPurchaseorder) {
		return R.ok(fyAssetPurchaseorderService.updateById(fyAssetPurchaseorder));
	}

	/**
	 * 通过id删除采购订单
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除采购订单", notes = "通过id删除采购订单")
	@SysLog("通过id删除采购订单")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(fyAssetPurchaseorderService.removeById(id));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param searchDTO 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_export')")
	public List<PurchaseOrderExcelVO> export(PurchaseorderSearchDTO searchDTO) {
		return fyAssetPurchaseorderService.listPurchaseOrder(SpliceQueryWrapper.spliceSearchCondition(searchDTO));
	}

	/**
	 * 创建采购对象
	 *
	 * @return 采购对象
	 */
	@GetMapping("/create")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_add')")
	public R create() {
		return R.ok(this.fyAssetPurchaseorderService.create());
	}

	@GetMapping("/edit/{id}")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_edit')")
	public R edit(@PathVariable("id") Long id) {
		return R.ok(this.fyAssetPurchaseorderService.edit(id));
	}

	@ApiOperation(value = "分页查询带清单信息", notes = "分页查询带清单信息")
	@GetMapping("/getPurchaseOrderPage")
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_view')")
	public R getPurchaseOrderPage(Page page, AssetPurchaseorder fyAssetPurchaseorder) {
		return R.ok(fyAssetPurchaseorderService.getPurchaseOrderPage(page, Wrappers.query(fyAssetPurchaseorder)));
	}


	@ApiOperation(value = "批量删除采购申请", notes = "批量删除采购申请")
	@SysLog("批量删除采购申请" )
	@DeleteMapping("/batchDelete" )
	@PreAuthorize("@pms.hasPermission('purchaseorder_fyassetpurchaseorder_del')" )
	public R batchDelete(@RequestBody List<Long> ids) {
		return fyAssetPurchaseorderService.batchDelete(ids);
	}

	@ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
	@PostMapping(value = "/draftEndCallback", produces = "application/json")
	@Override
	public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			AssetPurchaseorder purchaseorder = this.fyAssetPurchaseorderService.getOne(Wrappers.<AssetPurchaseorder>query().lambda().eq(AssetPurchaseorder::getId, id), false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseorder), String.format("未找到对应的业务数据：%s", id));
			purchaseorder.setStatus(AssetStatusEnum.PROCESSING.getCode());
			this.fyAssetPurchaseorderService.updateById(purchaseorder);
			return R.ok(purchaseorder,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
	}

	@ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
	@PostMapping(value = "/returnCallback", produces = "application/json")
	@Override
	public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			AssetPurchaseorder purchaseorder = this.fyAssetPurchaseorderService.getOne(Wrappers.<AssetPurchaseorder>query().lambda().eq(AssetPurchaseorder::getId, id), false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseorder), String.format("未找到对应的业务数据：%s", id));
			purchaseorder.setStatus(AssetStatusEnum.DRAFT.getCode());
			this.fyAssetPurchaseorderService.updateById(purchaseorder);
			return R.ok(purchaseorder,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
	}

	@ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
	@PostMapping(value = "/callback", produces = "application/json")
	@Override
	public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			AssetPurchaseorder purchaseorder = this.fyAssetPurchaseorderService.getOne(Wrappers.<AssetPurchaseorder>query().lambda().eq(AssetPurchaseorder::getId, id), false);
			Assert.isTrue(ObjectUtils.isNotEmpty(purchaseorder), String.format("未找到对应的业务数据：%s", id));
			String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.APPROVE.getCode();
			purchaseorder.setStatus(status);
			this.fyAssetPurchaseorderService.updateById(purchaseorder);
			return R.ok(purchaseorder,"修改状态成功");
		}
		return R.failed("未找到对应的业务数据");
	}

}
